package web

import (
	"encoding/json"
	"errors"
	"net/http"
	"strconv"
	//	"strings"
)

const (
	Context_Type_Html = "text/html"
	Context_Type_Text = "text/plain"
	Context_Type_Xml  = "text/xml"
	Context_Type_Gif  = "image/gif"
	Context_Type_Jpeg = "image/jpeg"
	Context_Type_Png  = "image/png"
	Context_Type_Json = "application/json"
)

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Params         Params
}

func (c *Context) Status(code int) {
	c.ResponseWriter.WriteHeader(code)
}
func (c *Context) Param(key string) string {
	//	c.Request.Form.Get()
	return c.Params.ByName(key)
}
func (c *Context) getString(key string) string {
	if c.Request.Method == "GET" {
		return c.Request.URL.Query().Get(key)
	} else if c.Request.Method == "POST" {
		return c.Request.Form.Get(key)
	}
	return ""

}
func (c *Context) GetString(key string) string { //获取字符串
	return c.getString(key)
}
func (c *Context) GetInt(key string) (int, error) { //获取int
	val := c.getString(key)
	return strconv.Atoi(val)
}
func (c *Context) GetBool(key string) (bool, error) { //获取布尔
	val := c.getString(key)
	if val == "ture" {
		return true, nil
	} else if val == "false" {
		return false, nil
	}
	return false, errors.New("no bool type")
}
func (c *Context) Json(data interface{}) error {
	dataByte, err := json.Marshal(data)
	if err != nil {
		return err
	}
	c.ResponseWriter.Header().Set("Content-Type", Context_Type_Json+";"+"charset=utf-8")
	c.ResponseWriter.Write(dataByte)
	return nil
}
